package alice.exercise.leetcode.middle;

import java.util.HashMap;
import java.util.Map;

/**
 * 1797. 设计一个验证系统
 *
 * @author Alice
 * @since 2023-02-09 星期四 8:45
 */
class AuthenticationManager {
  private final Map<String, Integer> tokenIdExpiredMap;
  private final int ttl;

  public AuthenticationManager(int timeToLive) {
    tokenIdExpiredMap = new HashMap<>();
    this.ttl = timeToLive;
  }

  public void generate(String tokenId, int currentTime) {
    tokenIdExpiredMap.put(tokenId, currentTime + ttl);
  }

  public void renew(String tokenId, int currentTime) {
    Integer expired = tokenIdExpiredMap.get(tokenId);
    if (expired == null || expired <= currentTime) {
      return;
    }
    tokenIdExpiredMap.put(tokenId, currentTime + ttl);
  }

  public int countUnexpiredTokens(int currentTime) {
    int count = 0;
    for (Integer time : tokenIdExpiredMap.values()) {
      if (time > currentTime) {
        count++;
      }
    }
    return count;
  }
}
